Kullback Leibler Divergence¶
- It's a metric used in information-theory to quantify how one probability distribution $P$ diverges from another probability distribution $Q$. $$\begin{equation*} D_{KL}(P \parallel Q) = \sum_i^n P(i) \log \left(\frac{P(i)}{Q(i)}\right) \end{equation*}$$ where $n$ is the number of observations and $Q(i)\neq 0$.
- In some text-books, it's also referred to as relative-entropy.
- It's assymetric in nature. i.e, $D_{KL}(P \parallel Q)\neq D_{KL}(Q \parallel P)$.
Example¶
Let's suppose we're given a dataset as to how many people like apple pie, orange pie and chocolate pie in 2 separate years.
| Year | Apple Pie | Orange Pie | Chocolate Pie |
|---|---|---|---|
| 2024 | 120 | 80 | 200 |
| 2025 | 150 | 65 | 220 |
Let's see if we can measure how much the data has changed from the year 2024 to 2025.
Loading and visualizing the data¶
In [1]:
import matplotlib.pyplot as plt
import numpy as np
# Example data
data_2024 = [120, 80, 200]
data_2025 = [150, 65, 220]
labels = ['Apple pie', 'Orange Pie', 'Chocolate Pie']
# Set the positions for the bars
x = np.arange(len(labels)) # Indices for x-axis (0, 1, 2, 3)
width = 0.35 # Width of each bar (adjust to control closeness)
# Create the figure and axis
fig, ax = plt.subplots()
# Plot the bars
ax.bar(x - width/2, data_2024, width, label = '2024', color = '#1f77b4')
ax.bar(x + width/2, data_2025, width, label = '2025', color = '#ff7f0e')
# Customize the plot
ax.set_xlabel('Categories')
ax.set_ylabel('Values')
ax.set_title('Data Chart 2024-2025')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# Display the plot
plt.tight_layout()
plt.show()
Implementing KL divergence¶
In [2]:
import numpy as np
from typing import List
# Normalize the arrays to create probability distributions
def normalize_array(arr: List[float], epsilon_: float = 1e-10) -> List[float]:
arr_sum = np.sum(arr)
if arr_sum == 0:
raise ValueError("Array sum is zero, cannot normalize.")
# Add small epsilon to avoid division by zero
return (np.array(arr) + epsilon_) / (arr_sum + epsilon_ * len(arr))
# Compute KL divergence
def kl_divergence(p: List[float], q: List[float], epsilon_: float = 1e-10, normalize: bool = False) -> float:
normalized_p = (normalize_array(p, epsilon_ = epsilon_) if normalize else np.array(p))
normalized_q = (normalize_array(q, epsilon_ = epsilon_) if normalize else np.array(q))
# TODO: values less than epsilon are set to epsilon and values greater than 1 are set to 1
if normalize:
normalized_p = np.clip(normalized_p, epsilon_, 1)
normalized_q = np.clip(normalized_q, epsilon_, 1)
return np.sum(normalized_p * np.log10(normalized_p / normalized_q))
Driver code¶
In [3]:
kl_divergence(data_2024, data_2025, epsilon_ = 0.0, normalize = True)
Out[3]:
0.004695245214963049
Verification using scipy¶
In [4]:
import numpy as np
from scipy.stats import entropy
p = np.array(data_2024) / sum(data_2024)
q = np.array(data_2025) / sum(data_2025)
result = entropy(p, q, base = 10)
In [5]:
result
Out[5]:
0.004695245214963049